package com.zyg.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.alibaba.fastjson2.JSON;
import com.zyg.pojo.User;
import com.zyg.service.UserService;

import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LoginController {
    @Autowired
    private UserService userService;
    @RequestMapping("/")
    public String login() {
        return "login";
    }
    @RequestMapping("/login")
    public String login(User user, HttpSession session, String code) {
        String sessionCode = (String) session.getAttribute("code");
        if(!sessionCode.equalsIgnoreCase(code)) {
            return "redirect:/";
        }else{
            User u=userService.login(user);
            if(u!=null){
                //存储用户id
                StpUtil.login(u.getId());
               //if(userService.login(user)){
                return "redirect:/toindex";
            } else {
                return "redirect:/";
            }
        }
    }
    @ResponseBody
    @RequestMapping("/codeImage")
    public String imgCode(HttpSession session) {
        //清除session中的验证码
        session.removeAttribute("code");
        //调用HUtool工具类生成验证码
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        String code=captcha.getCode();
        session.setAttribute("code",code);
        return JSON.toJSONString(captcha.getImageBase64());
    }
}
